package com.atguigu.juc.cf;

import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

/**
 * @author yanglin
 * @create 2024-01-02 9:07 星期二
 * description:
 */
public class CompletableFutureUseDemo {


    @Test
    public void testCompletableFutureUser2() throws ExecutionException, InterruptedException {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        
        try {
            CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + " come in");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("1秒中后出结果，" + result);
                return result;
            },threadPool).whenComplete((v,e) -> {     //正常情况下的回调函数（使用非默认线程池）
                if (e == null){
                    System.out.println("...计算完成，更新系统 " + v);
                }
            }).exceptionally(e -> {        //异常情况下的回调函数
                e.printStackTrace();
                System.out.println("异常情况：" + e.getCause() + "\t" + e.getMessage());
                return null;
            });

            System.out.println(Thread.currentThread().getName() + "先去忙其他任务");
            
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
        
        //主线程不要立刻结束，延时3秒钟，否则CompletableFuture默认使用的线程池会立刻关闭：暂停3秒钟线程
        TimeUnit.SECONDS.sleep(3);
    }
    
    /**
     * CompletableFuture 代替 Future 案例
     */
    @Test
    public void testCompletableFutureUse() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("1秒中后出结果，" + result);
            return result;
        });

        System.out.println(Thread.currentThread().getName() + "先去忙其他任务");
        System.out.println(completableFuture.get());
    }
    
    
}
